from django.shortcuts import render

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from meiduo_all.libs.captcha.captcha import captcha
from rest_framework.generics import GenericAPIView
# from libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
import random
from . import constants
from . import serializers
import logging
# Create your views here.
logger = logging.getLogger('django')

# /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
# /sms_codes/18500001111/?image_code_id=123456&text=zxcv
class SMSCodeView(GenericAPIView):
    '''
    发送短信验证码
    '''
    #指定序列化器
    serializer_class = serializers.ImageCodeCheckSerializer
    def get(self,request,mobile):
        #获取序列化对象：需要将text和image_code_id这两个查询字符串传入到序列乎其对象中验证
        serializer = self.get_serializer(data = request.query_params) # request.query_params == image_code_id=123456&text=zxcv
        #开启验证
        serializer.is_valid(raise_exception = True)
#         生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.debug(sms_code)
        #存储短信验证码到 redis
        redis_conn = get_redis_connection('verify_codes')

        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 记录发送短信的标记
        pl.setex('send_flag_%s' % mobile, constants.SMS_CODE_REDIS_INTERVAL, 1)
        pl.execute()

        #发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES//60],constants.SMS_SEND_TEMPLATE_ID)
        send_sms_code.delay(mobile,sms_code)
        #响应json给vue,所以需要json数据格式，进而选择response
        return Response({'message':'Ok'})

class ImageCodeView(APIView):
    def get(self,request,image_code_id):
        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return HttpResponse(image,content_type='image/jpg')